import { _decorator, Component, Node, find, loader, Prefab, instantiate } from 'cc';
const { ccclass, property } = _decorator;

/**     UI界面管理器，主要用于窗口界面的打开和关闭      */

@ccclass('UIManager')
export class UIManager{
    //保存所有打开过的UI界面的Map(字典).
    static _dictPanel = new Map<string,Node>();

    //打开某个窗口的函数.
    public static showDialog(name:string,cb?:Function,...args:any[]){
        //把要打开的窗口的名称的第一个字符大写.
        const scriptName = (name.substr(0, 1)).toUpperCase() + name.substr(1);
        //如果窗口曾被打开过，在字典中有缓存，则直接取出该缓存的窗口节点对象，调用其show函数.
        if(this._dictPanel.has(name)){
            const panel = this._dictPanel.get(name);
            const parent = find('Canvas');
            panel.parent = parent;
            const comp = panel.getComponent(scriptName);
            //comp['show']是用于判断组件comp中是否有show方法.
            if(comp && comp['show']){
                comp['show'].apply(comp,args);
            }

            if(cb){
                cb();
            }

            return;
        }

        //如果该窗口从未打开过，则加载该窗口对应的预物体.
        const path = 'ui/'+scriptName;
        loader.loadRes(path,Prefab,(err:any, prefab:Prefab)=>{
            if(err){
                console.warn(err);
                return;
            }

            const panel = instantiate(prefab) as Node;
            this._dictPanel.set(name,panel);
            const parent = find('Canvas');
            panel.parent = parent;
            const comp = panel.getComponent(scriptName);
            //comp['show']是用于判断组件comp中是否有show方法.
            if(comp && comp['show']){
                comp['show'].apply(comp,args);
            }

            if(cb){
                cb();
            }
        });
    }

    //隐藏某个UI界面窗口.
    public static hideDialog(name:string,cb?:Function){
        if(this._dictPanel.has(name)){
            const panel = this._dictPanel.get(name);
            //将某个物体的父亲设置空(null)，在cocos creator3d里面，是常用的一种隐藏物体的手段.
            panel.parent = null;
            const scriptName = name.substr(0, 1).toUpperCase() + name.substr(1);
            const comp = panel.getComponent(scriptName);
            if(comp && comp['hide']){
                comp['hide'].apply(comp);
            }

            if(cb){
                cb();
            }
        }
    }
}
